package cn.com.thingo.hyintelligent.ui.activity;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.content.IntentFilter;
import android.os.Handler;
import android.os.Message;
import android.support.v4.app.ActivityCompat;
import android.support.v4.app.Fragment;
import android.view.KeyEvent;
import android.view.View;
import android.widget.ImageView;
import android.widget.RadioGroup;
import android.widget.TextView;

import com.th.opensdk.openapi.AlarmMessageInfo;
import com.th.opensdk.openapi.NotificationInfo;
import com.th.opensdk.openapi.SceneInfo;
import com.th.opensdk.openapi.THOpenSDK;
import com.videogo.openapi.EZOpenSDK;
import com.videogo.util.MD5Util;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.thingo.hyintelligent.R;
import cn.com.thingo.hyintelligent.app.EzHttpConstants;
import cn.com.thingo.hyintelligent.app.App;
import cn.com.thingo.hyintelligent.base.BaseActivity;
import cn.com.thingo.hyintelligent.base.contract.MainContract;
import cn.com.thingo.hyintelligent.download.DownloadApk;
import cn.com.thingo.hyintelligent.model.bean.BaseBean;
import cn.com.thingo.hyintelligent.model.bean.EzAccountBean;
import cn.com.thingo.hyintelligent.model.bean.GetEzTokenBean;
import cn.com.thingo.hyintelligent.model.bean.UserBean;
import cn.com.thingo.hyintelligent.model.db.UserInfo;
import cn.com.thingo.hyintelligent.model.bean.CommonBean;
import cn.com.thingo.hyintelligent.model.bean.MessageCountBean;
import cn.com.thingo.hyintelligent.presenter.MainPresenter;
import cn.com.thingo.hyintelligent.ui.adapter.WindowListAdapter;
import cn.com.thingo.hyintelligent.ui.fragment.ControlFragment;
import cn.com.thingo.hyintelligent.ui.fragment.MonitorFragment;
import cn.com.thingo.hyintelligent.ui.fragment.ScenesFragment;
import cn.com.thingo.hyintelligent.ui.receiver.THOpenReceiver;
import cn.com.thingo.hyintelligent.util.FragmentTabUtils;
import cn.com.thingo.hyintelligent.util.SPUtils;
import cn.com.thingo.hyintelligent.util.ToastUtil;
import cn.com.thingo.hyintelligent.util.WaitDialogUtils;
import cn.com.thingo.hyintelligent.widget.WaitDialog;

public class MainActivity extends BaseActivity<MainPresenter> implements MainContract.View, WindowListAdapter.CallBack {

    @BindView(R.id.toolbar_title)
    TextView tvTitle;
    @BindView(R.id.toolbar_left)
    ImageView ivLeft;
    @BindView(R.id.toolbar_right)
    ImageView ivRight;
    @BindView(R.id.message_count)
    TextView tvCount;
    @BindView(R.id.main_radio_group)
    RadioGroup rgMain;
    private String mMD5AccountName;
    private String mMD5Password;
    public static final String EZ_ACCESS_TOKEN_SUCCEED_ACTION = "SUCCEED";
    private List<Fragment> fragments = new ArrayList<>();
    //定义一个变量，来标识是否退出
    private static boolean isExit = false;
    @SuppressLint("HandlerLeak")
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            isExit = false;
        }
    };
    private THOpenReceiver receiver;
    private UserInfo mUserInfo;
    private WaitDialog mWaitDialog;

    @Override
    public boolean onKeyDown(int keyCode, KeyEvent event) {
        if (keyCode == KeyEvent.KEYCODE_BACK) {
            exit();
            return false;
        }
        return super.onKeyDown(keyCode, event);
    }

    private void exit() {
        if (!isExit) {
            isExit = true;
            ToastUtil.shortShow("再按一次退出程序");
            //利用handler延迟发送更改状态信息
            handler.sendEmptyMessageDelayed(0, 2000);
        } else {
            finish();
            System.exit(0);
        }
    }

    @Override
    protected int getLayout() {
        return R.layout.activity_main;
    }

    @Override
    protected void initEventAndData() {
        //1.注册下载广播接收器
        DownloadApk.registerBroadcast(this);
        //2.删除已存在的Apk
        DownloadApk.removeFile(this);
        mUserInfo = UserInfo.getInstance();
        initView();
        initReceiver();
        initAccessToken();


    }

    private void initAccessToken() {
        mWaitDialog = WaitDialogUtils.showWaitDialog(mContext);
        mWaitDialog.setWaitText("请等待初始化...");
        mMD5AccountName = MD5Util.getMD5String(mUserInfo.getUserName()).toLowerCase();
        mMD5Password = MD5Util.getMD5String(App.EZ_APP_Key + "#" + mUserInfo.getUserName()).toLowerCase();
        mPresenter.getAdminEzAccessToken(mUserInfo.getToken(), App.EZ_SECRET, App.EZ_APP_Key);

    }

    private void initReceiver() {
        receiver = new THOpenReceiver(this);
        IntentFilter filter = new IntentFilter();
        filter.addAction(NotificationInfo.BROADCAST_ALARM_MESSAGE_UPLOAD);
        filter.addAction(NotificationInfo.BROADCAST_DATA_UPDATED_FINISH);
        filter.addAction(NotificationInfo.BROADCAST_DATA_UPDATED_START);
        filter.addAction(NotificationInfo.BROADCAST_DEVICE_STATE_UPLOAD);
        filter.addAction(NotificationInfo.BROADCAST_GATEWAY_STATUS_CHANGED);
        registerReceiver(receiver, filter);

    }

    private void initView() {
        ivLeft.setImageResource(R.mipmap.more);
        ivRight.setImageResource(R.mipmap.message);
        tvTitle.setText(R.string.app_name);
        ivRight.setVisibility(View.VISIBLE);
        fragments.add(ControlFragment.newInstance());
        fragments.add(MonitorFragment.newInstance());
        fragments.add(ScenesFragment.newInstance());
        //从后台取得萤石云管理员账户token
        String token = SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN);
        FragmentTabUtils fragmentTabUtils = new FragmentTabUtils(getSupportFragmentManager(), fragments, R.id.main_fragment, rgMain);
        fragmentTabUtils.setInitEzRefresh(new FragmentTabUtils.InitEzCallback() {
            @Override
            public void refreshEz() {
                initAccessToken();
            }
        });
        fragmentTabUtils.onCheckedChanged(rgMain, rgMain.getChildAt(0).getId());
    }

    @Override
    public void onBackPressedSupport() {
        if (getSupportFragmentManager().getBackStackEntryCount() > 1) {
            pop();
        } else {
            ActivityCompat.finishAfterTransition(this);
        }
    }


//    @Override
//    public void doUpdate(UpdateBean updateBean) {
//        final String url = updateBean.getData().getUrl();         //更新url
//        final String content = updateBean.getData().getContent();         //更新的内容
//
//        new MaterialDialog.Builder(MainActivity.this)
//                .title("更新")
//                .content(content)
//                .positiveText("立即更新")
//                .negativeText("以后再说")
//                .positiveColor(mContext.getResources().getColor(R.color.gray_6))
//                .negativeColor(mContext.getResources().getColor(R.color.gray_6))
//                .onPositive(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        //3.如果手机已经启动下载程序，执行downloadApk。否则跳转到设置界面
//                        if (DownLoadUtils.getInstance(getApplicationContext()).canDownload()) {
//                            DownloadApk.downloadApk(getApplicationContext(), url, "更新", "找找");
//                        } else {
//                            DownLoadUtils.getInstance(getApplicationContext()).skipToDownloadManager();
//                        }
//                    }
//                })
//                .onNegative(new MaterialDialog.SingleButtonCallback() {
//                    @Override
//                    public void onClick(@NonNull MaterialDialog dialog, @NonNull DialogAction which) {
//                        dialog.dismiss();
//                    }
//                })
//                .show();
//    }

    public void callBackMessage(AlarmMessageInfo alarmMessageInfo) {
        mPresenter.addMessage(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN), "报警消息", "网关:".concat(SPUtils.newInstance().getString(SPUtils.GATEWAY_CURRENT_NAME)).concat("触发").concat(alarmMessageInfo.getMessage()));

    }

    @OnClick({R.id.toolbar_left, R.id.toolbar_right})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.toolbar_left:
                //个人中心
                Intent personalIntent = new Intent(mContext, PersonalActivity.class);
                startActivityForResult(personalIntent, 500);
                break;
            case R.id.toolbar_right:
                //消息中心
                Intent messageIntent = new Intent(mContext, MessageActivity.class);
                startActivity(messageIntent);
                break;
        }
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 500 && resultCode == 500) {
            Intent intent = new Intent(mContext, LoginActivity.class);
            startActivity(intent);
            finish();
        }
    }

    @Override
    protected void onDestroy() {
        //4.反注册广播接收器
        //有时报反注册失败crash  Receiver not registered 应该需要用try catch
        DownloadApk.unregisterBroadcast(this);
        super.onDestroy();
        unregisterReceiver(receiver);
        THOpenSDK.getInstance().logoutGateway();
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }



    @Override
    public void viewCreateEzAccountResult(BaseBean ezAccountBean) {
        int state = ezAccountBean.getStatus();
        switch (state) {
            case 1:
                mPresenter.getSonAccountMsg(mUserInfo.getToken(), mUserInfo.getAccessToken());
                break;
            default:
                if (mWaitDialog != null) {
                    mWaitDialog.dismiss();
                }
                break;

        }
        ToastUtil.shortShow(ezAccountBean.getMsg());
    }



    @Override
    public void viewGetAdminEzAccessToken(BaseBean<String> ezTokenBean) {
        int status = ezTokenBean.getStatus();
        switch (status) {
            case 1:
                String accessToken = ezTokenBean.getData();
                mUserInfo.setAccessToken(accessToken);
                mPresenter.getSonAccountMsg(mUserInfo.getToken(), accessToken);
                break;
            default:
                ToastUtil.shortShow("获取萤石信息失败");
                break;
        }

    }

    @Override
    public void getSonAccountMsg(BaseBean<EzAccountBean> bean) {
        switch (bean.getStatus()) {
            case 1:
                mUserInfo.setAccountId(bean.getData().getAccount_id());
                mUserInfo.setRamAccessToken(bean.getData().getSon_access_token());
                EZOpenSDK.getInstance().setAccessToken(bean.getData().getSon_access_token());
                if (mWaitDialog!=null){
                    mWaitDialog.dismiss();
                }
                break;
            case 0:
                mPresenter.createEzAccount(mUserInfo.getToken(), mMD5AccountName, mMD5Password, mUserInfo.getAccessToken());
                break;
        }
    }

    @Override
    public void ezInitError() {
        if (mWaitDialog!=null){
            mWaitDialog.dismiss();
        }
    }

    @Override
    public void callBack(final SceneInfo sceneInfo) {
        if (App.getInstance().isScenesStatus()) {
            //场景开关控制
            App.getInstance().setScenesStatus(false);
            long controlId = sceneInfo.getControlId();
            App.getInstance().setCurrentScenesId(controlId);
            new Thread() {
                @Override
                public void run() {
                    super.run();
                    sceneInfo.run();
                }
            }.start();
        } else {
            ToastUtil.shortShow("有其他窗户的操作正在部署中...");
        }
    }

    @Override
    public void viewAddMessage(CommonBean commonBean) {
        mPresenter.messageCount(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN));

    }

    @Override
    protected void onResume() {
        super.onResume();
        mPresenter.messageCount(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN));
    }


    @Override
    public void viewMessageCount(MessageCountBean messageCountBean) {
        int count = Integer.valueOf(messageCountBean.getCount());
        if (count > 0) {
            tvCount.setVisibility(View.VISIBLE);
            if (count > 10) {
                tvCount.setText("9+");
            } else {
                tvCount.setText(String.valueOf(count));
            }
        } else {
            tvCount.setVisibility(View.GONE);
        }

    }


}
